<template>
	<view>
		<match-media :min-width="800">
			<view class="uni-header">
				<view class="uni-group">
					<input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
					<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
					<button class="uni-button" type="default" size="mini" @click="uploadFile">上传</button>
					<button class="uni-button" type="default" size="mini" @click="newFilder">新建文件夹</button>
					<button class="uni-button" type="primary" size="mini" @click="returnUpper">⇠</button>
					<button class="uni-button" type="primary" size="mini" @click="refreshCurrentDir">
						<image src="/static/icons/refresh_icon.png" class="refresh_icon"></image>
					</button>
				</view>
			</view>
		</match-media>
		<match-media :max-width="400">
			<view class="uni-header" style="height: 200rpx;flex-direction: column;justify-content: space-around;padding-top: 20rpx;">
				<view class="uni-group">
					<input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
					<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
					<button class="uni-button" type="default" size="mini" @click="uploadFile">上传</button>
				</view>
				<view class="uni-group" style="padding-bottom: 20rpx;">
					<button class="uni-button" type="default" size="mini" @click="newFilder">新建文件夹</button>
					<button class="uni-button" type="primary" size="mini" @click="returnUpper">⇠</button>
					<button class="uni-button" type="primary" size="mini" @click="refreshCurrentDir">
						<image src="/static/icons/refresh_icon.png" class="refresh_icon"></image>
					</button>
				</view>
			</view>
		</match-media>
		<view class="directorys">
			<text v-for="(item, index) in directoryList" :key="index" @tap="returnDirector(index)">
				{{ item.name }}
				<image src="/static/icons/right_icon.png" class="right_icon"></image>
			</text>
		</view>
		<view class="uni-container">
			<unicloud-db
				ref="udb"
				collection="file_list_catch"
				page-data="replace"
				:orderby="orderby"
				:getcount="true"
				:page-size="options.pageSize"
				:page-current="options.pageCurrent"
				v-slot:default="{ data, pagination, loading, error, options }"
				:options="options"
				@load="setPageData"
			>
				<!-- 文件视图 -->
				<view class="file_continor">
					<template v-if="cureentFileList.length > 0">
						<view v-for="(item, index) in cureentFileList" :key="index" class="file_one_continor" @longpress="fileLongPress(item, true)">
							<template v-if="item.file.fileType.indexOf('image') >= 0">
								<image class="cover" :src="item.file.url" lazy-load @tap="preImg(item.file.url)"></image>
							</template>

							<template v-else-if="item.file.fileType == 'fileder'">
								<image class="cover" src="/static/imgs/fileder_icon.png" lazy-load @tap="inFileder(item._id, item.file.name)"></image>
							</template>

							<template v-if="item.file.fileType.indexOf('video') >= 0">
								<video class="cover" :src="item.file.url" lazy-load @tap="seeVideo(item.file.url)"></video>
							</template>

							<!-- 文件名 -->
							<view class="file_name">{{ item.file.name }}</view>

							<!-- 更多按钮 -->
							<image src="/static/icons/more_icon.png" class="more_icon" lazy-load></image>

							<!-- 更多菜单 -->
							<view class="right_menus">
								<view>打开</view>
								<view @tap="fileLongPress(item, false)">重命名</view>
								<view @tap="copyFilePath(item)">复制path地址</view>
								<view @tap="copyFileUrl(item)">复制url地址</view>
								<view @tap="delFile_info(item)">删除</view>
								<view @tap="seeFileDetail(item)">属性</view>
							</view>
						</view>
					</template>
					<template v-else>
						<view class="no_data">
							<image src="/static/icons/no_data.png"></image>
							<view>这里是空的哟~</view>
						</view>
					</template>
				</view>
				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current" :total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>
		</view>

		<!-- 新建文件夹 -->
		<uni-popup ref="setName" type="center">
			<view class="file_rename">
				<input type="text" v-model="fileName" auto-focus style="margin-bottom: 50rpx;" placeholder="请输入名称" @confirm="newFilerPack" />
				<button type="primary" @tap="newFilerPack">确定</button>
			</view>
		</uni-popup>

		<!-- 删除重命名操作pop -->
		<uni-popup ref="appRenamePop" type="center">
			<view class="file_rename" style="padding: 50rpx 30rpx;">
				<view class="option_file_img" v-if="optionFile.file">
					<image :src="optionFile.file.url" lazy-load v-if="optionFile.file.fileType.indexOf('image') >= 0"></image>
					<image src="/static/imgs/fileder_icon.png" lazy-load v-else-if="optionFile.file.fileType == 'fileder'"></image>
				</view>

				<uni-forms>
					<uni-forms-item label="重命名:" name="">
						<input type="text" auto-focus v-model="fileName" placeholder="请输入名称" style="margin-left: -40rpx;" @confirm="renameFile" />
					</uni-forms-item>
				</uni-forms>
				<view style="display: flex;justify-content: space-around;width: 90%;">
					<button type="primary" @tap="renameFile">确定</button>
					<button type="warn" @tap="delFile" v-if="isShowDelBtn">删除文件</button>
				</view>
			</view>
		</uni-popup>

		<!-- 文件详情属性pop -->
		<uni-popup ref="fileDetailPop" type="center">
			<view class="file_detail" style="padding: 50rpx 30rpx;">
				<view class="option_file_img" v-if="optionFile.file">
					<image :src="optionFile.file.url" lazy-load v-if="optionFile.file.fileType.indexOf('image') >= 0"></image>
					<image src="/static/imgs/fileder_icon.png" lazy-load v-else-if="optionFile.file.fileType == 'fileder'"></image>
				</view>

				<!-- 详情 -->
				<view v-if="optionFile.file" class="file_info">
					<view>
						<text class="keys">文件名：</text>
						<text>{{ optionFile.file.name }}</text>
					</view>
					<view>
						<text class="keys">文件类型：</text>
						<text>{{ optionFile.file.fileType }}</text>
					</view>
					<view>
						<text class="keys">文件url地址：</text>
						<text>{{ optionFile.file.url }}</text>
					</view>
					<view>
						<text class="keys">文件路径：</text>
						<text>{{ optionFile.file.path }}</text>
					</view>
					<view>
						<text class="keys">文件大小：</text>
						<text>
							<template v-if="optionFile.file.size == '未知'">
								未知
							</template>
							<template v-else>
								{{
									optionFile.file.size / 1024 > 999 ? (optionFile.file.size / 1024 / 1024).toFixed(2) + 'MB' : (optionFile.file.size / 1024).toFixed(2) + 'KB'
								}}({{ optionFile.file.size }}字节)
							</template>
						</text>
					</view>
				</view>

				<view style="display: flex;justify-content: space-around;width: 90%;"><button type="primary" @tap="closeFileDetailPop">确定</button></view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
// import { enumConverter } from '@/js_sdk/validator/file_list.js';
import fileMVU from './vuex_util.js';

const db = uniCloud.database();
const dbOrderBy = 'sort desc'; // 排序字段
// 表查询配置
const dbSearchFields = ['file.name']; // 模糊搜索字段，支持模糊搜索的字段列表
// 分页配置
const pageSize = 20;
const pageCurrent = 1;

export default {
	data() {
		return {
			query: '',
			oldQuery: '',
			options: {
				pageSize,
				pageCurrent
				// ...enumConverter
			},
			orderby: dbOrderBy,
			cureentFileList: [], //当前文件列表
			fileName: '', //新建文件夹的文件名
			directoryList: [
				// {
				// 	//深度list
				// 	path: '//',
				// 	name: '根目录',
				// 	id:
				// }
			],
			optionFile: {}, //当前操作的文件，用于手机端长按删除操作
			isShowDelBtn: true //重命名pop是否显示删除按钮
		};
	},
	methods: {
		search() {
			// 相同条件时，手动强制刷新
			const dirList = fileMVU.getDirectory();
			const index = dirList.findIndex(item => {
				return item.path == '//searchacquizhang';
			});
			if (index < 0) {
				this.directoryList.push({
					path: '//searchacquizhang',
					name: '搜索'
				});
				fileMVU.setDirectory([
					{
						path: '//searchacquizhang',
						name: '搜索'
					}
				]);
			}
			if (this.oldQuery == this.query) {
				return;
			}
			this.oldQuery = this.query;
			// 开始搜索
			this.getDataScrren(this.query, true);
		},
		loadData(clear = true) {
			this.$refs.udb.loadData({
				clear
			});
		},
		onPageChanged(e) {
			this.$refs.udb.loadData({
				current: e.current
			});
		},
		navigateTo(url, clear) {
			// clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
			uni.navigateTo({
				url,
				events: {
					refreshData: () => {
						this.loadData(clear);
					}
				}
			});
		},
		confirmDelete(id) {
			this.$refs.udb.remove(id);
		},
		// 设置页面数据
		setPageData(e) {
			// console.log(this.$store.state.file_manage.fileLists);
			fileMVU.setFileList(e, false);
			this.getDataScrren();
			this.getDirectory();
		},
		// 获取当前目录下的文件
		getDataScrren(condition, isAll) {
			this.cureentFileList = fileMVU.getFileList(isAll, condition);
		},
		// 获取目录地址
		getDirectory() {
			this.directoryList = [...fileMVU.getDirectory()];
		},
		//上传文件
		uploadFile() {
			uniCloud.chooseAndUploadFile({
				type: 'all',
				onUploadProgress: res => {
					let progress = (res.loaded / res.total) * 100 + '';
					progress = progress.substring(0, 5);

					console.log(res);

					uni.showLoading({
						title: `正在上传第${res.index + 1}个文件  ${progress}%`
					});
				},
				success: res => {
					console.log(res);

					uni.hideLoading();
					const ress = res.tempFiles;
					let tips = '文件上传成功！';

					let errNameList = [];
					ress.forEach(async item => {
						if (item.errMsg == '文件上传失败') {
							errNameList.push(item.name);
						} else {
							// console.log(item);
							// 获取尺寸信息
							if (item.type.indexOf('image') >= 0) {
								await new Promise(resolve => {
									uni.getImageInfo({
										src: item.url,
										success: e => {
											item.moreDetail = e;
										},
										complete: () => {
											resolve();
										}
									});
								});
							}else if(item.type.indexOf('video') >= 0){
								await new Promise(resolve => {
									uni.getVideoInfo({
										src: item.url,
										success: e => {
											item.moreDetail = e;
										},
										complete: () => {
											resolve();
										}
									});
								});
							}
							// 新增数据
							const addObj = {
								file: {
									name: item.name,
									fileType: item.type,
									url: item.url,
									path: this.directoryList[this.directoryList.length - 1].path,
									size: item.size,
									more_detail:item.moreDetail?item.moreDetail:{}
								},
								father_id: this.directoryList[this.directoryList.length - 1].id ? this.directoryList[this.directoryList.length - 1].id : '//:',
								createTime: Date.now()
							};

							this.$refs.udb.add(addObj, {
								success: res => {
									// console.log(res);
									// 新增成功后的回调
									addObj._id = res.result.id;
									this.cureentFileList.push(addObj);
									fileMVU.setFileList([addObj]);
								},
								fail: err => {
									// 新增失败后的回调
									const { message } = err;
									uni.showToast({
										title: message,
										icon: 'none'
									});
								}
							});
						}
					});
					if (errNameList.length === ress.length) {
						tips = '文件上传失败！';
					} else if (errNameList.length > 0) {
						tips = `文件${errNameList.join('、')}上传失败！`;
					}

					uni.showToast({
						title: tips,
						icon: 'none',
						duration: 2000
					});
				},
				fail: () => {
					uni.hideLoading();
					uni.showToast({
						title: '上传失败！',
						icon: 'none'
					});
				}
			});
		},
		// 新建文件夹
		newFilder() {
			this.$refs.setName.open();
		},
		// 新建文件夹
		async newFilerPack() {
			if (!this.fileName) {
				uni.showToast({
					title: '请填写文件名！',
					icon: 'none'
				});
				return;
			}
			// 判断文件名是否存在
			const lists = fileMVU.getFileList(true);
			const index = lists.findIndex(item => {
				return item.file.name == this.fileName && item.file.fileType == 'fileder' && item.file.path == this.directoryList[this.directoryList.length - 1].path;
			});
			if (index >= 0) {
				uni.showToast({
					title: '该名称已经存在啦！请重新弄一个名称🙃',
					icon: 'none',
					duration: 2000
				});
				this.fileName = '';
				this.$refs.setName.close();
				return;
			}
			// console.log(networkFileInfo);
			// 新增数据
			const addObj = {
				file: {
					name: this.fileName,
					fileType: 'fileder',
					url: '',
					size: '未知'
				},
				father_id: this.directoryList[this.directoryList.length - 1].id ? this.directoryList[this.directoryList.length - 1].id : '//:',
				createTime: Date.now(),
				sort: 100
			};

			this.$refs.udb.add(addObj, {
				toastTitle: '新增成功', // toast提示语
				success: res => {
					// 新增成功后的回调
					// const { code, message } = res;
					addObj._id = res.result.id;
					this.$refs.setName.close();
					this.cureentFileList.push(addObj);
					fileMVU.setFileList([addObj]);
					this.fileName = '';
				},
				fail: err => {
					// 新增失败后的回调
					const { message } = err;
					uni.showToast({
						title: message,
						icon: 'none'
					});
				}
			});
		},
		// 文件长按
		fileLongPress(item, isShowDelBtn) {
			this.isShowDelBtn = isShowDelBtn;
			this.fileName = item.file.name;
			this.optionFile = item;
			this.$refs.appRenamePop.open();
		},
		// 查看详情属性
		seeFileDetail(item) {
			item.file.path = fileMVU.getFilePath(item.father_id, item.file.name);
			this.optionFile = item;
			this.$refs.fileDetailPop.open();
		},
		// 关闭查看详情属性
		closeFileDetailPop() {
			this.$refs.fileDetailPop.close();
		},
		copyFilePath(item) {
			uni.setClipboardData({
				data: item.file.path,
				success: () => {
					uni.showToast({
						title: 'path复制成功！',
						icon: 'none'
					});
				}
			});
		},
		copyFileUrl(item) {
			uni.setClipboardData({
				data: item.file.url,
				success: () => {
					uni.showToast({
						title: 'url复制成功！',
						icon: 'none'
					});
				}
			});
		},
		// 文佳重命名
		renameFile() {
			const fileNewInfo = this.optionFile.file;
			fileNewInfo.name = this.fileName + '';
			this.$refs.udb.update(
				this.optionFile._id + '',
				{
					file: fileNewInfo
				},
				{
					toastTitle: '修改成功', // toast提示语
					success: () => {
						this.fileName = '';
						this.$refs.appRenamePop.close();
					}
				}
			);
		},
		// 删除文件
		delFile() {
			let ids = [];
			let idsObj = fileMVU.getFileIds(this.optionFile);
			idsObj.push(this.optionFile);
			idsObj.forEach(item => {
				ids.push(item._id);
			});

			const user = uni.getStorageSync('userInfo');
			// console.log(this.optionFile);
			this.$refs.udb.remove(ids, {
				confirmContent: '您是否确认删除该文件以及其所有的子文件?',
				success: async () => {
					uni.showToast({
						title: '删除成功！',
						icon: 'none'
					});
					db.collection('del-log').add({
						table_name: 'file_list_catch',
						del_data: { idsObj },
						del_time: new Date().getTime(),
						optioner_id: user._id,
						optioner_name: user.username
					});
					this.$refs.appRenamePop.close();
				}
			});
		},
		// 删除文件
		delFile_info(item) {
			// console.log(item);
			this.optionFile = item;
			this.delFile();
		},
		// 进入文件夹
		inFileder(id, name) {
			uni.showLoading({
				title: '加载中~'
			});
			// const cureentPath = path + name + '/';
			this.directoryList.push({
				id: id,
				name: name
			});
			fileMVU.setDirectory([
				{
					id: id,
					name: name
				}
			]);
			this.getDataScrren();
			uni.hideLoading();
		},
		// 返回上一级
		returnUpper() {
			uni.showLoading({
				title: '加载中~'
			});
			uni.hideLoading();
			if (this.directoryList.length > 1) {
				this.directoryList.splice(-1);
				fileMVU.setDirectory(this.directoryList, false);
				this.getDataScrren();
			} else {
				uni.showToast({
					title: '已经是根目录啦😡',
					icon: 'none',
					duration: 2500
				});
				return;
			}
		},
		// 返回到指定路径
		returnDirector(index) {
			if (index + 1 >= this.directoryList.length) return;
			this.directoryList = this.directoryList.splice(0, index + 1);
			fileMVU.setDirectory(this.directoryList, false);
			this.getDataScrren();
		},
		// 刷新当前目录
		refreshCurrentDir() {
			this.loadData();
			uni.showToast({
				title: '刷新成功！',
				icon: 'none',
				duration: 2000
			});
		},
		// 预览图片
		preImg(url) {
			uni.previewImage({
				urls: [url]
			});
		},
		// 查看视频
		seeVideo(url) {
			const video = uni.createVideoContext(url, this);
			console.log(video);
			video.requestFullScreen();
		}
	}
};
</script>
<style lang="less" scoped>
.refresh_icon {
	width: 30rpx;
	height: 30rpx;
}
.directorys {
	padding-left: 40rpx;
	padding-bottom: 20rpx;
	border-bottom: 1px solid red;
	& > text {
		padding: 10rpx;
	}
	& > text:hover {
		background-color: #e5f3ff;
		cursor: pointer;
	}
	.right_icon {
		width: 20rpx;
		height: 20rpx;
		padding-left: 10rpx;
	}
}
.file_continor {
	display: flex;
	align-items: center;
	align-items: center;
	flex-wrap: wrap;
	width: 100%;
	.cover {
		width: 200rpx;
		height: 200rpx;
		border-radius: 20rpx;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
	}
	// image:hover .more_icon{
	// 	opacity: 0;
	// }
	.file_one_continor {
		position: relative;
		.more_icon {
			width: 60rpx;
			height: 60rpx;
			// border: 2px solid #6ceeb2;
			// color: #6ceeb2;
			// border-radius: 50%;
			position: absolute;
			top: 0px;
			right: 0rpx;
			// text-align: center;
			// line-height: 40rpx;
			// font-size: 40rpx;
			opacity: 0;
		}
		.more_icon:hover {
			cursor: pointer;
		}
		.more_icon:hover + .right_menus {
			display: inline-block;
		}
		.right_menus {
			width: 300rpx;
			background-color: #eeeeee;
			border: 1px solid gray;
			position: absolute;
			top: 20px;
			right: -130px;
			z-index: 5;
			display: none;
			& > view {
				padding: 15rpx 40rpx;
				cursor: pointer;
			}
			& > view:hover {
				background-color: white;
			}
		}
		.right_menus:hover {
			display: inline-block;
		}
	}
	.file_one_continor:hover {
		background-color: #e5f3ff;
	}
	.file_one_continor:hover .more_icon {
		opacity: 1;
	}
	.no_data {
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;
		flex-direction: column;
		color: gray;
		width: 100%;
		padding-bottom: 100rpx;
		& > image {
			width: 400rpx;
			height: 400rpx;
		}
	}

	.file_name {
		text-align: center;
		font-size: 30rpx;
		color: gray;
		width: 200rpx;
		overflow: hidden;
	}
	.file_name:hover {
		width: 100%;
		overflow: inherit;
	}
}

.add_btn_b_r {
	position: absolute;
	bottom: 20rpx;
	right: 20rpx;
}

.file-modal,
.upfile-modal {
	width: 350px;
	background-color: #fff;
	height: auto;
	padding: 50rpx;
	border-radius: 10rpx;
}

@media screen and (min-width: 768px) {
	.file-modal-pc {
		width: 70vw;
		height: 33vw;
		display: flex;
		flex-direction: row;
	}
	.upfile-modal-pc {
		width: 50vw;
		height: 15vw;
		display: flex;
		flex-direction: row;
	}
	.file_one_continor {
		padding: 30rpx;
	}
	/deep/.uni-forms-item__label {
		margin-right: 20px !important;
	}
}
.file_rename {
	background-color: white;
	width: 600rpx;
	height: 500rpx;
	border-radius: 15rpx;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	input {
		border: 1px solid #5894e2;
		padding: 20rpx 30rpx;
		// margin-bottom: 50rpx;
		border-radius: 10rpx;
	}
}
.file_detail {
	background-color: white;
	width: 700rpx;
	height: 730rpx;
	border-radius: 15rpx;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	font-size: 30rpx;
	color: gray;
	.keys {
		width: 100rpx;
		font-size: 35rpx;
		font-weight: bold;
	}
	.file_info > view {
		padding: 10rpx 0;
	}
}

.option_file_img > image {
	width: 200rpx;
	height: 200rpx;
	border-radius: 15rpx;
	margin-bottom: 50rpx;
}
</style>
